<script>
  import { tick } from "svelte";

  import ImagePicker from "../components/ImagePicker.svelte";

  const PIXEL_SIZE = 4;

  let canvas;
  let imageWidth = 100;
  let imageHeight = 100;
  let textImageArea;

  let charList = "@#$%&80=>+;-".split("");
  const getChar = (uint8 = 0) => {
    const RANGE = 256;
    const size = charList.length;
    return charList[~~((uint8 * size) / RANGE)];
  };

  const pickedHandler = async ({ detail }) => {
    const { preview: image } = detail;
    imageWidth = image.width;
    imageHeight = image.height;
    await tick();

    const ctx = canvas.getContext("2d");
    ctx.drawImage(image, 0, 0, imageWidth, imageHeight);
    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    const textImage = imageToText(imageData);
    textImageArea.innerHTML = textImage;
  };

  function imageToText(imageData) {
    const { data, width } = imageData;
    let text = "";
    let row = 1;
    for (let i = 0; i < data.length; i = i + PIXEL_SIZE) {
      const avg = 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];
      text += getChar(avg);
      if (i / PIXEL_SIZE + 1 == width * row) {
        row++;
        text += "<br/>";
      }
    }
    return text;
  }
</script>

<canvas bind:this={canvas} width={imageWidth} height={imageHeight} />
<ImagePicker on:picked={pickedHandler} />
<hr />
<div
  bind:this={textImageArea}
  width={imageWidth * 12}
  height={imageHeight * 6}
  class="text-image"
/>

<style>
  canvas {
    display: none;
    background-color: #666;
  }
  .text-image {
    /* text-align: center; */
    font-family: monospace;
    /* Chrome 最小12px */
    font-size: 12px;
    line-height: 6px;
  }
</style>
